import { URL } from '../api/config'
import axios from 'axios'
import { message } from 'antd'
import history from "../lib/history";
import store from '../store'

const service = axios.create({
    baseURL: URL,
    timeout: 6000
})

let { num } = store.getState()

service.interceptors.request.use(
     config =>{
         let token = num
         if (token) {
             config.headers['Authorization'] = `${token}`
         }else {
             token = localStorage.getItem('token')
             if (token){
                 config.headers['Authorization'] = `${token}`
             }else {
                 history.push('/login')
             }
         }
         return config
    },
    error =>{
        message.error(error)
        return Promise.reject(error)
    }
)

service.interceptors.response.use(response => {
        const { code} = response.data
        if (code === 0) {
            return response.data
        } else {
            message.error(response.data.message)
            if (response.data.message === '身份认证失败!'){
                history.push('/login');
            }
            return Promise.reject(new Error(response.data.message))
        }
    },
    error => {
        history.push('/login')
        message.error(error.message)
        return Promise.reject(error)
    })

export default service
